package com.sgj.controller.admin;

import com.sgj.pojo.User;
import com.sgj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author 沈国纪
 * @date 2021/3/30 10:42
 */
@Controller
@RequestMapping("/admin")
public class LoginController {

	private static final String INDEX = "admin/index";
	private static final String LOGIN = "admin/login";
	private static final String REDIRECT_LOGIN = "redirect:/admin";

	@Autowired
	private UserService userService;

	/**
	 * 跳转到登陆页面
	 * @return
	 */
	@GetMapping
	public String loginPage() {
		return LOGIN;
	}

	/**
	 * 用户登录
	 * @param username
	 * @param password
	 * @return
	 */
	@PostMapping("/login")
	public String login(@RequestParam("username") String username,
	                    @RequestParam("password") String password,
	                    HttpSession session,
	                    RedirectAttributes attributes) {
		// 判断用户是否存在
		User user = userService.checkUser(username, password);
		if (Objects.nonNull(user)) {
			// 不要将密码传到 session 中
			user.setPassword(null);
			session.setAttribute("user", user);
			return INDEX;
		} else {
			attributes.addFlashAttribute("message", "用户名和密码错误");
			return REDIRECT_LOGIN;
		}
	}

	/**
	 * 注销
	 * @param session
	 * @return
	 */
	@GetMapping("/logout")
	public String logout(HttpSession session) {
		// 删掉 session 中的 user
		session.removeAttribute("user");
		return REDIRECT_LOGIN;
	}
}
